import React from "react";
import {IGridCellRenderParam} from "./grid_type";
import Grid from "./grid";
import {Select} from 'antd'
import {toJS} from "mobx";
import {getSelectData, YvanEventDispatch} from "../../utils/helper";
import _ from 'lodash'

interface SelectEditorProp extends IGridCellRenderParam {
    $context: any

    colDef: {
        /**
         * 渲染函数
         */
        data: any[]
        onChange: (event: any) => void
        instanceScope: any
    }

    grid: Grid
}

interface SelectEditorState {
    value: any
}

export default class SelectEditor extends React.Component<SelectEditorProp, SelectEditorState> {

    constructor(props: SelectEditorProp) {
        super(props);

        this.state = {
            value: _.trim(props?.value)
        }
    }

    handleChange(value: any) {
        this.setState({
            value
        }, () => {
            YvanEventDispatch(this.props.colDef.onChange, this.props.colDef?.instanceScope, value, this.props.rowIndex, this.props.data)
        })
    }

    render() {
        const data = getSelectData(toJS(this.props.colDef.data))

        return (
            <Select
                showSearch
                optionFilterProp="label"
                filterOption={(input, option) =>
                    // @ts-ignore
                    option.label?.indexOf(input) >= 0
                }
                options={data.map(v => ({value: v.id, label: v.text}))}
                value={this.state.value}
                style={{width: '100%'}}
                onChange={this.handleChange.bind(this)}
            />
        );
    }

    getValue(): any {
        return this.state.value
    }
}